//
//  Topic_getTopicList_tv_cell.m
//  ainkjj
//
//  Created by MAX on 2020/4/30.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Topic_getTopicList_tv_cell.h"
#import "SDImageCache.h"

#import "Tiezi_pinglun_vc.h"
#import "StringCalculateManager.h"


const UIEdgeInsets kInsets = {30, 32, 30, 32};
const CGFloat kAvatarSize = 38;
const CGFloat kAvatarMarginRight = 10;
const CGFloat kAvatarMarginBottom = 12;
const CGFloat kContentMarginBotom = 12;

@implementation Topic_getTopicList_tv_cell

- (void)didInitializeWithStyle:(UITableViewCellStyle)style {
    [super didInitializeWithStyle:style];
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    self.contentView.backgroundColor = UIColor.groupTableViewBackgroundColor;
    _bgV = [UIView new];
    [self.contentView addSubview:_bgV];
    _bgV.backgroundColor = UIColor.whiteColor;
    _bgV.layer.masksToBounds = YES;
    _bgV.layer.cornerRadius = 5;
    
    _avatarImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.avatarImageView];
    _avatarImageView.layer.masksToBounds = YES;
    _avatarImageView.layer.cornerRadius = kAvatarSize * 0.5;
    _nameLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(16) textColor:rgb(17,17,17)];
    [self.contentView addSubview:self.nameLabel];
    
    
    _timeLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(15) textColor:UIColor.qd_descriptionTextColor];
    [self.contentView addSubview:self.timeLabel];
    
    _contentLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(17) textColor:UIColor.qd_mainTextColor];
    self.contentLabel.numberOfLines = 0;
    [self.contentView addSubview:self.contentLabel];
    
    _x_btn = [UIButton new];
    [self.contentView addSubview:_x_btn];
    [_x_btn setImage:UIImageMake(@"close_icon") forState:UIControlStateNormal];
    [_x_btn addTarget:self action:@selector(x_btn_action:) forControlEvents:UIControlEventTouchUpInside];
    _iv1 = [UIImageView new];
    [self.contentView addSubview:_iv1];
    _iv2 = [UIImageView new];
    [self.contentView addSubview:_iv2];
    _iv3 = [UIImageView new];
    [self.contentView addSubview:_iv3];
    self.ivArr = @[_iv1, _iv2, _iv3];
    
    for (UIImageView *iv in self.ivArr) {
        iv.layer.cornerRadius = 5;
        iv.layer.masksToBounds = YES;
//        [iv setContentMode:UIViewContentModeScaleAspectFit];
        [iv setContentMode:UIViewContentModeScaleAspectFill];
    }
    
    _btn1 = [QMUIButton new];
    [self.contentView addSubview:_btn1];
    

    _btn2 = [QMUIButton new];
    [self.contentView addSubview:_btn2];
    
    _btn3 = [QMUIButton new];
    [self.contentView addSubview:_btn3];
    
    [_btn1 setTitleColor:rgb(244,110,23) forState:UIControlStateSelected];
    [_btn1 setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
    [_btn2 setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
    [_btn3 setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];

    self.btnArr = @[_btn1, _btn2, _btn3];
    NSArray *imgs = @[@"praise_icon", @"comment_icon", @"share_icon"];
    for ( NSUInteger i = 0; i < self.btnArr.count ; i++) {
        QMUIButton *b = self.btnArr[i];
//        b.tintColorAdjustsTitleAndImage = UIColor.qd_tintColor;
        b.imagePosition = QMUIButtonImagePositionLeft;
        b.spacingBetweenImageAndTitle = 8;
        [b setImage:UIImageMake(imgs[i]) forState:UIControlStateNormal];
        b.titleLabel.font = UIFontMake(16);
        b.titleLabel.textColor = rgb(244,110,23);
//        b.qmui_borderPosition = QMUIViewBorderPositionTop | QMUIViewBorderPositionBottom;
        if (i == 0) {
            [b setImage:UIImageMake(@"praise_selected_icon") forState:UIControlStateSelected];
        }
        b.tag = i;
        [b addTarget:self action:@selector(threeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}
- (void)threeBtnClick:(QMUIButton *)sender{
        
    switch (sender.tag) {
        case 0:
            [self dianzan_action:sender];
            break;
            
        case 1:
        {
            Tiezi_pinglun_vc *vc= [[Tiezi_pinglun_vc alloc]init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.model = self.model;
            [[Anktool viewControllerForView:self].navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 2:
        {
            NSInteger count = MIN(30, self.model.content.length);
            NSString *desc = [self.model.content substringWithRange:NSMakeRange(0, count)];
            [Anktool fenxiangTopic:self.model.ID name:self.model.name desc:desc currentView:self];
        }
            break;
            
            
    }
}


- (NSAttributedString *)attributeStringWithString:(NSString *)textString lineHeight:(CGFloat)lineHeight {
    if (textString.qmui_trim.length <= 0) return nil;
    NSAttributedString *attriString = [[NSAttributedString alloc] initWithString:textString attributes:@{NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:lineHeight lineBreakMode:NSLineBreakByCharWrapping textAlignment:NSTextAlignmentLeft]}];
    return attriString;
}

- (CGSize)sizeThatFits:(CGSize)size {
    CGSize resultSize = CGSizeMake(size.width, 0);
    CGFloat contentLabelWidth = size.width - UIEdgeInsetsGetHorizontalValue(kInsets);
    
    CGFloat resultHeight = UIEdgeInsetsGetHorizontalValue(kInsets) + CGRectGetHeight(self.avatarImageView.bounds) + kAvatarMarginBottom;
    
    if (self.contentLabel.text.length > 0) {
//        CGSize contentSize = [self.contentLabel sizeThatFits:CGSizeMake(contentLabelWidth, CGFLOAT_MAX) ];
//        resultHeight += (contentSize.height + kContentMarginBotom);
        // 法二
        CGSize contentSize =  [self.contentLabel.text boundingRectFastWithMaxWidth:contentLabelWidth withFont:self.contentLabel.font].size;

        resultHeight += (contentSize.height + kContentMarginBotom);
        
    }

    
    // 图片固定布局
    CGFloat ivW = (ScreenWidth - kInsets.left - kInsets.right - 7 * 2) / 3.0;
    CGFloat ivH = ivW * 84 / 100.0;
   
    
    resultHeight += 10;

    if (self.model.files.count > 0) {
        resultHeight += ivH + 10;
    }
    
        resultHeight = ivW * 46 / 100.0 + resultHeight;
    
    
    
    
    resultSize.height = resultHeight;
//    DLog(@"%@ 的 cell 的 sizeThatFits: 被调用（说明这个 cell 的高度重新计算了一遍）", self.nameLabel.text);
    return resultSize;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat contentLabelWidth = CGRectGetWidth(self.contentView.bounds) - UIEdgeInsetsGetHorizontalValue(kInsets);
    self.avatarImageView.frame = CGRectMake(kInsets.left, kInsets.top, kAvatarSize, kAvatarSize);
    if (self.nameLabel.text.length > 0) {
        CGFloat nameLabelWidth = contentLabelWidth - CGRectGetWidth(self.avatarImageView.bounds) - kAvatarMarginRight - 44;
        CGSize nameSize = [self.nameLabel sizeThatFits:CGSizeMake(nameLabelWidth, CGFLOAT_MAX)];
        self.nameLabel.frame = CGRectFlatMake(CGRectGetMaxX(self.avatarImageView.frame) + kAvatarMarginRight, CGRectGetMinY(self.avatarImageView.frame), nameLabelWidth, nameSize.height);
    }
    
    self.x_btn.frame = CGRectMake(contentLabelWidth  , 8, 44, 44);
    
    if (self.timeLabel.text.length > 0) {
        CGSize timeSize = [self.timeLabel sizeThatFits:CGSizeMake(contentLabelWidth, CGFLOAT_MAX)];
        self.timeLabel.frame = CGRectFlatMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + 4, contentLabelWidth, timeSize.height);
        
    }
    if (self.contentLabel.text.length > 0) {
//        CGSize contentSize = [self.contentLabel sizeThatFits:CGSizeMake(contentLabelWidth, CGFLOAT_MAX)];
//        self.contentLabel.frame = CGRectFlatMake(kInsets.left, CGRectGetMaxY(self.avatarImageView.frame) + kAvatarMarginBottom, contentLabelWidth, contentSize.height);
        // 法二
        CGSize contentSize =  [self.contentLabel.text boundingRectFastWithMaxWidth:contentLabelWidth withFont:self.contentLabel.font].size;
        self.contentLabel.frame = CGRectFlatMake(kInsets.left, CGRectGetMaxY(self.avatarImageView.frame) + kAvatarMarginBottom, contentLabelWidth, contentSize.height);

    }
    
    // 图片固定布局
    CGFloat ivW = (ScreenWidth - kInsets.left - kInsets.right - 7 * 2) / 3.0;
    CGFloat ivH = ivW * 84 / 100.0;
    for (NSInteger i = 0; i < self.ivArr.count; i++) {
        UIImageView *iv = self.ivArr[i];
        iv.frame = CGRectMake( kInsets.left + i * (ivW + 7), CGRectGetMaxY(self.contentLabel.frame) + 10, ivW, ivH);
    }
    
    // 按钮布局依据 是否有图片
    CGFloat btnMaxY = CGRectGetMaxY(self.iv1.frame);
    if (self.model.files.count == 0) {
        btnMaxY = CGRectGetMaxY(self.contentLabel.frame) + 10;
    }
    for (NSInteger i = 0; i < self.btnArr.count; i++) {
        QMUIButton *b = self.btnArr[i];
        b.frame = CGRectMake( kInsets.left + i * (ivW + 7), btnMaxY, ivW, ivW * 46 / 100.0);
        b.titleLabel.textColor = rgb(244,110,23);

    }
    
    self.bgV.frame = CGRectMake(kInsets.left * 0.5, kInsets.top * 0.25, ScreenWidth - kInsets.left, CGRectGetMaxY(self.btn1.frame) + 6);
}
- (void)setModel:(Topic_getTopicListFindtopicpagedto *)model{
    _model = model;
        
    [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.avatarUrl] placeholderImage:UIImageMake(@"mine_head_icon")];
    self.nameLabel.text = model.nickName;
    self.contentLabel.text = model.name;
    self.timeLabel.text = model.addTime;
    
    
    
    // 图片赋值，如果有就赋值，没有就赋值为空
    NSUInteger imgCount = MIN(3, model.files.count);
    for (NSInteger i = 0; i < self.ivArr.count; i++) {
        UIImageView *iv = self.ivArr[i];
        if (i < imgCount) {
            NSString *fileUrl = model.files[i];
            NSURL *u = [NSURL URLWithString:fileUrl];
            if ([fileUrl containsString:@".mp4"] || [fileUrl containsString:@".mov"]) {
                NSString *cacheKey =  [SDWebImageManager.sharedManager cacheKeyForURL:u];
                
                
                
                SDImageCache *sd_cache = SDImageCache.sharedImageCache;
                
                [SDWebImageManager.sharedManager.imageCache queryImageForKey:cacheKey options:0 context:nil cacheType:SDImageCacheTypeAll completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
                   
                    if (image) {
                        iv.image = image;

                    }else{
                        
                        
                        dispatch_async(dispatch_get_global_queue(0, 0), ^(void) {
                            AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:fileUrl] options:nil];
                            AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
                            
                            assetGen.appliesPreferredTrackTransform = YES;
                            CMTime time = CMTimeMakeWithSeconds(0.0, 600);
                            NSError *error = nil;
                            CMTime actualTime;
                            CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
                            UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
                            CGImageRelease(image);
                            [sd_cache storeImage:videoImage forKey:cacheKey completion:^{
                                
                            }];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                iv.image = videoImage;
                                
                            });
                        });
                        
                    }
                }];
                
                
                
               
            }else{
                [iv sd_setImageWithURL:[NSURL URLWithString:fileUrl]];

            }
        }else{
            iv.image = nil;
        }
    }
    if (imgCount == 0) {
        for (UIImageView *iv in self.ivArr) {
            iv.image = nil;
        }
    }
    // 按钮赋值
    [self.btn1 setTitle:@(model.praiseNum).stringValue forState:UIControlStateNormal];
    
    if (model.praiseStatus == 1) {
        self.btn1.selected = NO;
    }else{
        self.btn1.selected = YES;
    }
    
    [self.btn2 setTitle:@(model.discussNum).stringValue forState:UIControlStateNormal];
        
    [self.btn3 setTitle:@(model.transmitSum).stringValue forState:UIControlStateNormal];
}

- (void)dianzan_action:(QMUIButton *)sender{
    sender.userInteractionEnabled = NO;
    
    NSString *url = sender.isSelected == YES ? @"java/app/topic/repealTopicLike" : @"java/app/topic/topicLike";
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@(self.model.ID).stringValue forKey:@"topicId"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:url parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            
            
            
            if (sender.selected) {
                self.model.praiseNum -=1;
            }else{
                self.model.praiseNum +=1;
            }
            sender.selected =  !sender.isSelected ;

            [self.btn1 setTitle:@(self.model.praiseNum).stringValue forState:UIControlStateNormal];

        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"]];
            
        }
        sender.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription] ];
        sender.userInteractionEnabled = YES;
    }];
}
- (void)x_btn_action:(UIButton *)sender{
    sender.userInteractionEnabled = NO;
    
    QMUITips *t = [QMUITips showLoadingInView:[Anktool viewControllerForView:self].view];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@(self.model.ID).stringValue forKey:@"topicId"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:@"java/app/topic/topicShield" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            if (self.blk) {
                self.blk(self.idxPath);
            }
            [t hideAnimated:NO];
        }
        else{
            
            [t showError:response[@"error_msg"] hideAfterDelay:1.5];
            
        }
        
        sender.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        [t showError:[error localizedDescription] ];
        sender.userInteractionEnabled = YES;
    }];
}
@end
